﻿using Help;
using Model;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

namespace BLLA
{
    public partial class Order_UserSendAddr : BaseBLL<Model.Order_UserSendAddr>, IBLL.IOrder_UserSendAddrBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();
        IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");

        public string GetUserSendAddr(string OpenId, string MerId, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                var z = bl.IOrder_UserSendAddrBLL.GetListBy(u => u.OpenId == OpenId);
                if (MerId != "")
                {
                    List<int> vs = bl.IOrder_MerSend_TBLL.GetListBy(u => u.MerId == MerId).Select(u => u.MerSendAddId).ToList();
                    //z = (from m in z where vs.Contains(m.AddId) select m).ToList();
                }
                List<Model.View_OrderUserSendAddr> view_OrderUserSendAddrs = new List<View_OrderUserSendAddr>();
                foreach (var item in z)
                {
                    view_OrderUserSendAddrs.Add(new View_OrderUserSendAddr()
                    {
                        ID = item.ID,
                        //AddName = item.Order_MerSendAdd_T.AddName,
                        //AddId = item.AddId,
                        Name = item.Name,
                        AddrContent = item.AddrContent,
                        TelNum = item.TelNum
                    });
                }
                result.rows = view_OrderUserSendAddrs;
                string bbb = os.StringOfObject(result, 1);
                result.total = z.Count;
                result.rows = view_OrderUserSendAddrs;
                result.BS = "1";
                result.Msg = "查询成功";

            }
            catch (Exception ex)
            {
                WriteLog.WriteW("GetUserSendAddr异常：" + ex.Message);
                result.BS = "-99";
                result.Msg = "操作失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        /// <summary>
        /// 获取用户已经添加的地址
        /// </summary>
        /// <param name="OpenId">微信ID</param>
        /// <param name="AccID">用户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string GetAllUserSendAddr(string OpenId, int AccID, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                List<Model.Order_UserSendAddr> UserSendAddr = base.GetListBy(u => u.AccID == AccID && u.OpenId == OpenId).ToList();
                
                if (UserSendAddr != null && UserSendAddr.Count() > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功！";
                    result.rows = UserSendAddr;
                    result.total = UserSendAddr.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据！";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("GetUserSendAddr异常：" + ex.Message);
                result.BS = "-99";
                result.Msg = "操作失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        /// <summary>
        /// 更新用户的配送地址
        /// </summary>
        /// <param name="json">更新信息</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetUserSendAddr(string json, int tag, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_UserSendAddr info = ParseClass<Model.Order_UserSendAddr>.StrDeserialize(json, RETID);
                string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (tag)
                {
                    case 1:
                        T = "新增";
                        ret = base.Add(info);
                        //Help.ComdSqlFactory cmd = new ComdSqlFactory();
                        //cmd.ExecuteScalar("INSERT INTO  Order_UserSendAddr (AddId,Name,AddrContent,TelNum,OpenId) VALUES(" + info.AccID + ",'"+info.Name+ "','" + info.AddrContent + "','" + info.TelNum + "','" + info.OpenId + "' )");
                        ret = 1;
                        break;
                    case 2:
                        T = "修改"; 
                        ret = base.Modify(info); 
                        break;
                    case 3:
                        T = "删除";
                        WriteLog.WriteW("SetUserSendAddr" + json);
                        List<Model.Order_UserSendAddr> list_tmp = base.GetListBy(u => true).Where(x => x.ID == info.ID).ToList();
                        if (list_tmp != null && list_tmp.Count > 0)
                        {
                            Model.Order_UserSendAddr tmp = list_tmp.First();
                            ret = base.Del(tmp);
                        }
                        //cmd = new ComdSqlFactory();
                        //cmd.ExecuteScalar("delete from Order_UserSendAddr  where ID=" + info.ID);
                        //ret = 1;
                        break;
                }

                if (ret > 0)
                { 
                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (DbEntityValidationException dbex)
            {
                StringBuilder errors = new StringBuilder();
                IEnumerable<DbEntityValidationResult> validationResult = dbex.EntityValidationErrors;
                foreach (DbEntityValidationResult result1 in validationResult)
                {
                    ICollection<DbValidationError> validationError = result1.ValidationErrors;
                    foreach (DbValidationError err in validationError)
                    {
                        errors.Append(err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                    }
                }
                //Console.WriteLine(errors.ToString());
                WriteLog.WriteW("更新用户配送地址信息异常DbEntity：" + errors.ToString());

                result.BS = "-99";
                result.Msg = "系统异常";
            }
            catch (DbUpdateException ex)
            { 
                WriteLog.WriteW(" 更新用户配送地址信息异常DbUpdate   " + ex.InnerException.Message);
                result.BS = "-99";
                result.Msg = "系统异常";
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新用户配送地址信息异常：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统异常";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

    }
}
